<template>
	<view class="container">
		<uni-forms v-model="form" label-position="left" label-width="80" :rules="rules" ref="form"
			validateTrigger="blur">
			<uni-forms-item required label="电表号" name="electricityNo">
				<u-button @click="meterSelectShow=true" plain hairline
					:text="form.electricityNo ? form.electricityNo : '点击选择电表' "></u-button>
			</uni-forms-item>
			<uni-forms-item required label="电流类型" name="currentTypeCode">
				<uni-data-checkbox v-model="form.currentTypeCode" :localdata="currentTypeOptions"
					@change="selectCurrentType"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item required name="currentValue" label="电流值">
				<uni-easyinput type="number" @blur="computePueValue" v-model.number="form.currentValue" trim
					:placeholder="beforeForm.electricityBillDegree ? '上期：'+beforeForm.electricityBillDegree : '请输入电流值'" />
			</uni-forms-item>
			<uni-forms-item required name="electricityBillDegree" label="电表度数">
				<uni-easyinput type="number" @blur="computePueValue" v-model.number="form.electricityBillDegree" trim
					:placeholder="beforeForm.electricityBillDegree ? '上期：'+beforeForm.electricityBillDegree : '请输入电表度数'" />
			</uni-forms-item>
			<uni-forms-item name="pueValue" label="pue值">
				<uni-easyinput type="number" v-model="form.pueValue" placeholder="自动计算" disabled />
			</uni-forms-item>
			<uni-forms-item required name="pueValue" label="电流照片">
				<u-upload :fileList="fileList1" @afterRead="afterRead1" @delete="deletePic" name="1" multiple deletable
					previewImage accept="image" :maxCount="9" :sizeType="['original']"></u-upload>
				<!-- <uni-file-picker v-model="fileList1" @select="selectFile1" ref="files1" limit="9"></uni-file-picker> -->
			</uni-forms-item>
			<uni-forms-item required name="pueValue" label="电表照片">
				<u-upload :fileList="fileList2" @afterRead="afterRead2" @delete="deletePic" name="1" multiple deletable
					previewImage accept="image" :maxCount="9" :sizeType="['original']"></u-upload>
				<!-- <uni-file-picker v-model="fileList2" @select="selectFile2" ref="files2" limit="9"></uni-file-picker> -->
			</uni-forms-item>
		</uni-forms>
		<u-button type="primary" text="确定" @click="confirmHandler"></u-button>
		<view class="before" @click="lookBefore">查看上期抄表记录</view>


		<!-- 消息通知 -->
		<u-toast ref="uToast"></u-toast>
		<!-- 上期抄表 -->
		<u-popup :show="beforeRecordShow" :round="20" mode="center" closeable @close="beforeRecordShow=false">
			<view class="before_record">
				<view class="record_title">上期抄表详情</view>
				<view class="record_content">
					<u-cell-group>
						<u-cell size="large" title="上期抄表时间" :label="beforeForm.meterReadingTime"></u-cell>
						<u-cell size="large" title="电流类型" :label="beforeForm.currentTypeName"></u-cell>
						<u-cell size="large" title="上期电流值" :label="beforeForm.currentValue"></u-cell>
						<u-cell size="large" title="上期电表度数" :label="beforeForm.electricityBillDegree"></u-cell>
						<u-cell size="large" title="上期用电量" :label="beforeForm.electricityConsumption"></u-cell>
						<u-cell size="large" title="上期pue值" :label="beforeForm.pueValue"></u-cell>
						<u-cell size="large" title="上期电流照片">
							<view slot="label" style="padding: 20rpx;">
								<u-swiper :list="beforeCurrentFileList" keyName="url"></u-swiper>
							</view>
						</u-cell>
						<u-cell size="large" title="上期电表照片">
							<view slot="label" style="padding: 20rpx;">
								<u-swiper :list="beforeMeterFileList" keyName="url"></u-swiper>
							</view>
						</u-cell>
					</u-cell-group>
				</view>
			</view>
		</u-popup>
		<!-- 选择电表 -->
		<u-popup :show="meterSelectShow" :round="20" @close="closePop">
			<view class="meter_select">
				<u--input placeholder="输入电表号搜索" border="surround" v-model="queryForm.electricityNo"
					@change="getMeterOptions"></u--input>
				<u-list height="500rpx">
					<u-list-item v-for="(item, index) in meterOptions" :key="index">
						<u-cell :title="item.electricityNo" @click="selectMeter(item)">
							<view slot="value">
								<u-tag v-if="item.ownerId && !item.operatorCode" text="业主侧" plain size="mini"
									shape="circle"></u-tag>
								<u-tag v-if="!item.ownerId && item.operatorCode" text="运营商侧" plain size="mini"
									shape="circle"></u-tag>
								<u-tag v-if="item.ownerId && item.operatorCode" text="业主侧" plain size="mini"
									shape="circle"></u-tag>
								<u-tag v-if="!item.ownerId && !item.operatorCode" text="未绑定" plain size="mini"
									shape="circle"></u-tag>
							</view>
						</u-cell>
					</u-list-item>
				</u-list>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		meterList,
		getBeforeRecord,
		sendMeter
	} from '@/apis/meter.js'
	import {
		BASE_URL
	} from '@/utils/request.js'
	import {
		parse
	} from 'json-bigint'
	export default {
		data() {
			return {
				form: {
					meterId: null,
					electricityNo: null,
					currentTypeCode: null,
					currentTypeName: null,
					currentValue: null,
					electricityBillDegree: null,
					pueValue: null,
					files: []
				},
				rules: {
					electricityNo: {
						rules: [{
							required: true,
							errorMessage: '请输入电表号',
						}]
					},
					currentTypeCode: {
						rules: [{
							required: true,
							errorMessage: '请选择电流类型'
						}]
					},
					currentValue: {
						rules: [{
							required: true,
							errorMessage: '请输入电流值',
							validateTrigger: 'blur'
						}]
					},
					electricityBillDegree: {
						rules: [{
							required: true,
							errorMessage: '请输入电表度数',
							validateTrigger: 'blur'
						}]
					}
				},
				currentTypeOptions: [{
						value: '10190001',
						text: '直流'
					},
					{
						value: '10190002',
						text: '交流'
					}
				],
				meterOptions: [],
				currentMeter: {},
				queryForm: {
					page: 1,
					size: 999,
					electricityNo: null
				},
				meterSelectShow: false,
				beforeRecordShow: false,
				fileList1: [],
				fileList2: [],
				beforeForm: {},
				beforeMeterFileList: [],
				beforeCurrentFileList: []
			}
		},
		onLoad(options) {
			if (options.data) {
				const data = JSON.parse(options.data)
				this.form.meterId = data.id
				this.form.electricityNo = data.electricityNo
				this.currentMeter = data
				this.getBeforeRecord(this.form.meterId)
			}
		},
		created() {
			this.getMeterOptions()
		},
		methods: {
			//获取电表列表
			async getMeterOptions() {
				const {
					data
				} = await meterList(this.queryForm)
				this.meterOptions = data.filter(i => i.status === 1)
			},
			//获取上期抄表记录
			async getBeforeRecord(id) {
				const {
					data
				} = await getBeforeRecord(id)
				this.beforeForm = data ? data : {}
				if (data) {
					this.beforeMeterFileList = data.list.filter(i => i.fileType === '0').map(i => ({
						id: i.id,
						url: i.fileUrl
					}))
					this.beforeCurrentFileList = data.list.filter(i => i.fileType === '1').map(i => ({
						id: i.id,
						url: i.fileUrl
					}))
				}
			},
			//选择电表
			selectMeter(item) {
				this.currentMeter = item
				this.form = {
					meterId: item.id,
					electricityNo: item.electricityNo,
					currentTypeCode: null,
					currentTypeName: null,
					currentValue: null,
					electricityBillDegree: null,
					pueValue: null,
					files: []
				}
				this.fileList1 = []
				this.fileList2 = []
				this.getBeforeRecord(item.id)
				this.meterSelectShow = false
			},
			//选择电流类型
			selectCurrentType(e) {
				this.form.currentTypeName = this.currentTypeOptions.filter(i => i.value === e.detail.value)[0].text
				this.computePueValue()
			},
			//读取图片
			afterRead1(e) {
				console.log(e)
				this.fileList1.push(...e.file)
				e.file.forEach(item => {
					console.log(item)
					uni.uploadFile({
						url: BASE_URL + '/v1/meterRead/uploadMeterImg',
						header: {
							'Content-Type': 'multipart/form-data',
							token: this.$store.state.user.token
						},
						filePath: item.url,
						fileType: 'image',
						name: 'multipartFile',
						formData: {
							'fileType': '1',
						},
						success: res => {
							const data = parse(res.data)
							this.form.files.push(String(data.data.id))
						},
						fail: err => {
							this.$refs.uToast.show({
								message: '图片上传失败',
								type: 'error'
							})
						}
					})
				})
			},
			//读取图片
			afterRead2(e) {
				this.fileList2.push(...e.file)
				e.file.forEach(item => {
					uni.uploadFile({
						url: BASE_URL + '/v1/meterRead/uploadMeterImg',
						header: {
							'Content-Type': 'multipart/form-data',
							token: this.$store.state.user.token
						},
						filePath: item.url,
						fileType: 'image',
						name: 'multipartFile',
						formData: {
							'fileType': '0',
						},
						success: res => {
							const data = parse(res.data)
							this.form.files.push(String(data.data.id))
						},
						fail: err => {
							this.$refs.uToast.show({
								message: '图片上传失败',
								type: 'error'
							})
						}
					})
				})
			},
			//上期抄表记录
			async lookBefore() {
				if (!this.form.electricityNo && !this.currentMeter.electricityNo) {
					return this.$refs.uToast.show({
						message: '请先选择电表',
						type: 'info',
						position: 'top'
					})
				}
				if (!this.beforeForm.id) {
					return this.$refs.uToast.show({
						message: '无上期抄表记录',
						type: 'info',
						position: 'top'
					})
				}
				this.beforeRecordShow = true
			},
			//抄表
			async confirmHandler() {
				await this.$refs.form.validate()
				if (this.beforeForm.electricityBillDegree && Number(this.form.electricityBillDegree) < this.beforeForm
					.electricityBillDegree) {
					return this.$refs.uToast.show({
						message: '本地度数不应小于上期度数',
						type: 'error',
						position: 'top'
					})
				}
				if (!this.fileList1.length || !this.fileList2.length) {
					return this.$refs.uToast.show({
						message: '电流照片和电表照片不能为空',
						type: 'error',
						position: 'top'
					})
				}
				const res = await sendMeter(this.form)
				if (res.errorMessage !== '操作成功') {
					return uni.showToast({
						title: res.errorMessage,
						type: 'error',
						duration: 1000
					})
				}
				uni.showToast({
					title: '抄表成功！',
					type: 'success',
					duration: 1000
				})
				setTimeout(() => {
					uni.redirectTo({
						url: `/pages/meter/sendRecords?data=${JSON.stringify(this.currentMeter)}`
					})
				}, 1000)
			},
			//pue值
			computePueValue() {
				if (!this.form.meterId || !this.form.currentValue || !this.form.electricityBillDegree) return
				const beforeUseCount = this.beforeForm.electricityConsumption ? Number(this.beforeForm
					.electricityConsumption) : 0 //上期用电量
				const currentUseCount = Number(this.form.electricityBillDegree) - (this.beforeForm.electricityBillDegree ?
					Number(this.beforeForm.electricityBillDegree) : this.currentMeter.initialElectricity ? this
					.currentMeter.initialElectricity : 0) //本期用电量
				const currentEleValue = Number(this.form.currentValue) //直流、交流负载
				const days = Math.ceil((new Date().getTime() - new Date(this.currentMeter.newData).getTime()) / (24 * 60 *
					60 * 1000))
				console.log(beforeUseCount, currentUseCount, days)
				this.form.pueValue = this.form.currentTypeCode === '10190001' ?
					((currentUseCount - beforeUseCount) / (24 * 54 * currentEleValue * days / 1000)).toFixed(2)
					.toString() :
					((currentUseCount - beforeUseCount) / (24 * 220 * currentEleValue * days / 1000)).toFixed(2).toString()
			},
			//重置
			rest() {
				this.form = {
					meterId: null,
					electricityNo: null,
					currentTypeCode: null,
					currentTypeName: null,
					currentValue: null,
					electricityBillDegree: null,
					pueValue: null,
					files: []
				}
				this.fileList1 = []
				this.fileList2 = []
				this.$refs.form && this.$refs.form.resetFields()
				this.$ref.files1 && this.$ref.files1.clearFiles()
				this.$ref.files2 && this.$ref.files2.clearFiles()
				this.currentMeter = {}
				this.beforeForm = {}
				this.beforeMeterFileList = []
				this.beforeMeterFileList = []
			},
			closePop() {
				this.meterSelectShow = false
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		padding: 30rpx;
		overflow: auto;

		.meter_select {
			padding: 30rpx;
			height: 600rpx;

			::v-deep .u-list {
				margin-top: 10rpx;
			}
		}

		.before_record {
			width: 640rpx;
			padding: 30rpx;
			height: 700rpx;
			display: flex;
			flex-direction: column;

			.record_title {
				height: 10%;
				font-size: 30rpx;
				font-weight: 700;
				margin-bottom: 10rpx;
			}

			.record_content {
				flex: 1;
				overflow: auto;
			}
		}

		.before {
			height: 80rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 28rpx;
			color: #8c8c8c;
		}
	}
</style>